package org.example.likou150.tree;

import com.sun.source.tree.Tree;

import java.util.*;

public class ZigzagLevelOrder {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);

        ZigzagLevelOrder zigzagLevelOrder = new ZigzagLevelOrder();
        zigzagLevelOrder.zigzagLevelOrder(root);
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root==null) return result;

        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        boolean isPre = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            isPre = !isPre;
            for (int i = 0; i < size; i++) {
                TreeNode node;
                if(isPre){
                    node = queue.pollLast();
                    if(node.right!=null) queue.addFirst(node.right);
                    if(node.left!=null) queue.addFirst(node.left);
                }else {
                    node = queue.pollFirst();
                    if(node.left!=null) queue.addLast(node.left);
                    if(node.right!=null) queue.addLast(node.right);
                }
                list.add(node.val);
            }
            result.add(list);
        }
        return result;
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
